import { useMessage } from '@hooks/useAppMessage'
import { useAxios } from '@hooks/useAxios'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { API_PRODUCT_CATEGORY_URL } from './baseApi'

export const useProductCategoryQuery = (params, enabled) => {
  const { http } = useAxios()
  return useQuery({
    queryKey: ['product.category.list', params],
    queryFn: async () => {
      return await http.get(API_PRODUCT_CATEGORY_URL, { params })
    },
    staleTime: 5000,
    enabled,
  })
}

export const useProductCategoryDetailQuery = (id) => {
  const { http } = useAxios()
  return useQuery({
    queryKey: ['product.category.detail', id],
    queryFn: async () => {
      const response = await http.get(`${API_PRODUCT_CATEGORY_URL}/${id}`)
      return response.data
    },
    enabled: !!id,
  })
}

export const useProductCategoryUpdateMutation = () => {
  const { http } = useAxios()
  const queryClient = useQueryClient()
  const message = useMessage()
  return useMutation({
    mutationFn: async (data) => {
      const response = await http.put(`${API_PRODUCT_CATEGORY_URL}/${data.id}`, data)
      return response.data
    },
    onSuccess: (data) => {
      console.log('product updated', data)
      queryClient.invalidateQueries(['product.category.list'])
      message.success('更新成功')
    },
  })
}

export const useProductCategoryCreateMutation = () => {
  const { http } = useAxios()
  const queryClient = useQueryClient()
  const message = useMessage()
  const navigate = useNavigate()
  return useMutation({
    mutationFn: async (data) => {
      const response = await http.post(API_PRODUCT_CATEGORY_URL, data)
      return response.data
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries(['product.category.list'])
      message.success('保存成功').then(() => navigate({ to: '..' }))
    },
  })
}

export const useProductCategoryDeleteMutation = () => {
  const { http } = useAxios()
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async (data) => await http.delete(`${API_PRODUCT_CATEGORY_URL}/${data.id}`),
    onSuccess: (data) => {
      queryClient.invalidateQueries(['product.category.list'])
    },
  })
}
